import fs from "fs-extra";
import path from "path";
import { isObject, logger } from ".";

import type { DeepRequired, PKG } from "../../types";
import type { CONFIG, SERVER_CONFIG } from "../../types/config";

export const CWD = process.cwd();
export const TEAMPLTE_PATH = path.resolve(__dirname, '../../templates')
export const RUN_TEMPLATE_PATH = path.resolve(__dirname, '../../_templates')
export const pkg: PKG = require(path.resolve(
  __dirname,
  "../",
  "../",
  "package.json"
));

export const loadConfig = function (root: string, configPath: string) {
  if (!fs.existsSync(configPath)) {
    logger.warn('no config file')
    process.exit(0)
  }
  const rootPkg = path.resolve(root, "package.json");
  let isEsm = false;
  let isTs = false
  if (fs.existsSync(rootPkg)) {
    try {
      let pkgContent: PKG = JSON.parse(fs.readFileSync(rootPkg, "utf-8"));
      if (pkgContent && pkgContent.type === "module") {
        isEsm = true;
      }
    } catch (error) {}
  }
  isTs = configPath.endsWith('.ts')
  if (configPath.endsWith('.mjs')) {
    isEsm = true
  }

};

export function mergeVmiServerOptions(
  defaultConfig: DeepRequired<SERVER_CONFIG>,
  opts: SERVER_CONFIG
): Required<SERVER_CONFIG> {
  const config: DeepRequired<SERVER_CONFIG> = { ...defaultConfig };
  const { port } = opts;
  if (typeof port === "number" && !Number.isNaN(port)) {
    config.port = port;
  }
  return config;
}

export function mergeVmiOptions(
  defaultConfig: DeepRequired<CONFIG>,
  opts: CONFIG
): DeepRequired<CONFIG> {
  let config: DeepRequired<CONFIG> = { ...defaultConfig };
  if (typeof opts.devServer !== undefined) {
    if (isObject(opts.devServer)) {
      config.devServer = mergeVmiServerOptions(
        config.devServer,
        opts.devServer
      );
    }
  }

  if (opts.root) {
    config.root = opts.root;
  }
  if (typeof opts.useConfigFile !== undefined) {
    config.useConfigFile = !!opts.useConfigFile;
  }
  if (isObject(opts.theme)) {
    config.theme = { ...config.theme, ...opts.theme };
  }

  return config;
}
